/*******************************************************************************
 *
 *    Copyright (c) Baina Info Tech Co. Ltd
 *
 *    RingtoneDownloader
 *    
 *    RateUSModel
 *    TODO File description or class description.
 *
 *    @author: zuochen
 *    @since:  2011-8-3
 *    @version: 1.0
 *
 ******************************************************************************/

package com.waps.util;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.widget.Toast;

import com.waps.AppConnect;
import com.waps.UpdatePointsNotifier;

/**
 * RateUSModel of RingtoneDownloader.
 * 
 * @author zuochen
 * 
 */

public class RateUSModel implements UpdatePointsNotifier{
	private static final String RATE_US_STATE = "rate_us_state";
	private static final String APP_RUN_TIMES = "app_run_times";
	private final Context mContext;
	private final SharedPreferences mSharedPreferences;
	private static RateUSModel sRateUSModel;
	private final static String IS_HAS_RATED = "is_has_rated";
	public static final String DEFAULT_RATE_APP_MESSAGE = "感谢你对我们的支持，为此，我们精心为您准备了一批优秀的程序，帮助你能更好的享受到安卓的乐趣!(还可以赚取积分哟！)";
	private static final String APP_SAVED_VERSION_CODE = "app_saved_version_code";

	private RateUSModel(Context context) {
		mContext = context;
		mSharedPreferences = PreferenceManager
				.getDefaultSharedPreferences(context);
	}

	public static RateUSModel getInstance(Context context) {
		if (null == sRateUSModel) {
			sRateUSModel = new RateUSModel(context);
		}
		return sRateUSModel;
	}

	// public void showAbout(){
	// final Intent intent = new Intent(mContext,AlertAboutActivity.class);
	// mContext.startActivity(intent);
	// }
	/**
	 * 设置是否显示about界面
	 * 
	 * @param isShowAbout
	 */
//	public void setIsShowAbout(boolean isShowAbout) {
//		this.isShowAbout = isShowAbout;
//	}

	/**
	 * 显示more apps
	 * 
	 * @param isShowWhenUpdate
	 *            当更新的时候是否显示
	 * @param frequency
	 *            显示rate的频率
	 * @param dialog
	 *            弹出的dialog，如果为空，则使用默认的弹出对话框.
	 */
	public void showMoreApps(boolean isShowWhenUpdate, int frequency) {
		if (isAppUpdated()) {
			if (isShowWhenUpdate) {
				setAppRunTimes(0);
				setIsHasRated(false);
			} else {
				setAppRunTimes(getAppRunTimes() + 1);
				return;
			}
			// no need else
		}// no need else
		if (isRunTimesEnoughToShow(frequency)) {
			showDefaultRateDialog();
		}
	}

	private static final String RUNS_TIMES = "runs_times";
	private static final long PER_DAY_TIMES = 24 * 60 * 60 * 1000;
	private static final String USER_POINT = "waps_users_point";

	public int getUserPoint() {
		return mSharedPreferences.getInt(USER_POINT, 0);
	}

	public void saveUserPoint(int userPoint) {
		mSharedPreferences.edit().putInt(USER_POINT, userPoint).commit();
	}
	public void initUserPoint(){
		AppConnect.getInstance(mContext).getPoints(
				this);
	}
	
	
	public static final int MAX_NEEDED_POINT =99;
	public boolean isShouldShowLicense(int days) {
//		if (getUserPoint()>MAX_NEEDED_POINT) {
//			return false;
//		}
		final long runsTimes = getRunsTimes();
		if (runsTimes == 0) {
			saveRungsTimes(System.currentTimeMillis());
			return false;
		}
		final long gapTime = System.currentTimeMillis() - runsTimes;
		if (gapTime < PER_DAY_TIMES * days) {
			return false;
		}
		return true;
	}

	/**
	 * 获取系统运行的时间
	 * 
	 * @return
	 */
	private long getRunsTimes() {
		return mSharedPreferences.getLong(RUNS_TIMES, 0);
	}

	/**
	 * 保存系统运行的时间
	 * 
	 * @param times
	 */
	private void saveRungsTimes(long times) {
		mSharedPreferences.edit().putLong(RUNS_TIMES, times).commit();
	}

	private void showDefaultRateDialog() {
		ShowMoreAppActivity.showMoreApps(mContext);
	}

	/**
	 * 判断app的运行次数时候足够弹出rating或者about
	 * 
	 * @param frequency
	 *            弹出的乏值
	 * @return true 弹出
	 */
	private boolean isRunTimesEnoughToShow(int frequency) {
		final int appRunTimes = getAppRunTimes();
		if (appRunTimes != 0 && appRunTimes % frequency == 0) {
			setAppRunTimes(getAppRunTimes() + 1);
			return true;
		}
		// if (appRunTimes == frequency + 1) {
		// if (isHasRated()) {
		// setAppRunTimes(getAppRunTimes() + 5);
		// return false;
		// }
		// increaseAppRunTimes();
		// return true;
		// }
		increaseAppRunTimes();
		return false;
	}

	/**
	 * 获取app的versioncode
	 * 
	 * @return versioncode for app.
	 */
	private int getAppVerionCode() {
		final PackageManager pm = mContext.getPackageManager();
		PackageInfo pi = null;
		try {
			pi = pm.getPackageInfo(mContext.getPackageName(), 0);
		} catch (final NameNotFoundException e) {
			e.printStackTrace();
		}
		return pi.versionCode;
	}

	private boolean isAppUpdated() {
		final int defualtVersionCode = getSavedVersionCode();
		final int nowAppVersionCode = getAppVerionCode();
		if (-1 == defualtVersionCode) {
			saveVersionCode(getAppVerionCode());
			return false;
		} else if (nowAppVersionCode > defualtVersionCode) {
			saveVersionCode(getAppVerionCode());
			return true;
		}
		return false;
	}

	/**
	 * 获取是否已经rate
	 * 
	 * @return
	 */
	private boolean isHasRated() {
		return mSharedPreferences.getBoolean(IS_HAS_RATED, false);
	}

	/**
	 * 设置是否已经rate
	 * 
	 * @param isHasRated
	 */
	public void setIsHasRated(boolean isHasRated) {
		mSharedPreferences.edit().putBoolean(IS_HAS_RATED, isHasRated).commit();
	}

	/**
	 * 获取已经保存的app的version code
	 * 
	 * @return
	 */
	private int getSavedVersionCode() {
		return mSharedPreferences.getInt(APP_SAVED_VERSION_CODE, -1);
	}

	/**
	 * 保存新的version
	 * 
	 * @param versionCode
	 */
	private void saveVersionCode(int versionCode) {
		mSharedPreferences.edit().putInt(APP_SAVED_VERSION_CODE, versionCode)
				.commit();
	}

	/**
	 * Goto market to do the rate for wally ringtone
	 * 
	 * @param context
	 */
	public static void gotoRate(Context context) {
		final Uri marketUri = Uri.parse("market://details?id="
				+ context.getPackageName());
		final Intent intent = new Intent(Intent.ACTION_VIEW, marketUri);
		try {
			context.startActivity(intent);
		} catch (final Exception e) {
			Toast.makeText(context, "No market client in your phone.",
					Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * Get rate us state <h1>The state means: whether the users had rate for us.
	 * </h1>
	 * 
	 * @param context
	 * @return
	 */
	public static boolean getRateUsState(Context context) {
		final SharedPreferences sharedPreferences = PreferenceManager
				.getDefaultSharedPreferences(context);
		return sharedPreferences.getBoolean(RATE_US_STATE, false);
	}

	/**
	 * Set the rate us state.
	 * 
	 * @param context
	 * @param rateUsState
	 */
	public static void setRateUsState(Context context, boolean rateUsState) {
		final SharedPreferences sharedPreferences = PreferenceManager
				.getDefaultSharedPreferences(context);
		sharedPreferences.edit().putBoolean(RATE_US_STATE, rateUsState)
				.commit();
	}

	/**
	 * 设置app 运行的次数
	 */
	public void setAppRunTimes(int times) {
		mSharedPreferences.edit().putInt(APP_RUN_TIMES, times).commit();
	}

	/**
	 * 自增app运行次数
	 */
	private void increaseAppRunTimes() {
		mSharedPreferences.edit().putInt(APP_RUN_TIMES, getAppRunTimes() + 1)
				.commit();
	}

	/**
	 * 获取app运行的次数 <h1>当update需要弹出about或者rate的时候将会归0</h1>
	 * 
	 * @return app运行的次数
	 */
	public int getAppRunTimes() {
		return mSharedPreferences.getInt(APP_RUN_TIMES, 0);
	}

	@Override
	public void getUpdatePoints(String arg0, int arg1) {
		saveUserPoint(arg1);
	}

	@Override
	public void getUpdatePointsFailed(String arg0) {
		
	}

}
